package com.itwn.portal.common.task;

import com.itwn.common.constant.RedisConst;
import com.itwn.portal.model.entity.BookType;
import com.itwn.portal.service.BookService;
import com.itwn.portal.service.BookTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class BookMallTask {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private BookService bookService;
    @Autowired
    private BookTypeService bookTypeService;

    /**
     * 定时任务作用： 每天凌晨定期更新Redis缓存； 实现缓存数据与数据库数据的同步
     */
    @Scheduled(cron = "0/20 * * * 6 ?")
    public void execute() {
        //1、删除所有以book:list开头的key
        redisTemplate.delete(redisTemplate.keys(RedisConst.BOOK_LIST+"*"));

        //2、查询热销榜数据，存入到Redis中：findTopSales
        bookService.findTopSales(1,12);

        //3、查询所有的分类，根据类别id查询图书放入Redis: findByType
        //3.1 删除所有以bookType:list开头的key
        redisTemplate.delete(redisTemplate.keys(RedisConst.BOOK_TYPE_LIST+"*"));
        //3.2 查询分类（自动放入Redis缓存）
        List<BookType> bookTypes = bookTypeService.findAll();
        //3.3 遍历所有类别，根据类别id分页查询图书
        bookTypes.forEach(bookType -> {
            bookService.findByType(1,12,bookType.getId());
        });
        log.info("更新MySQL中热销榜&图书类别&根据类别查询图书数据到Redis缓存");

    }
}
